import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-04-21
 * Time: 0:02
 */
//446.等差数列划分II-子序列
class Solution8 {
    public int numberOfArithmeticSlices(int[] nums) {
        //绑定元素,下标数组
        Map<Long,List<Integer>> hash = new HashMap<>();
        int n = nums.length;
        //优化
        for(int i = 0; i < n; i++) {
            //hash.put(nums[i],i);//会覆盖
            long tmp = (long)nums[i];
            if(!hash.containsKey(tmp)) {
                hash.put(tmp,new ArrayList<Integer>());
            }
            hash.get(tmp).add(i);
        }

        //创建dp表
        int[][] dp = new int[n][n];
        //dp[i][j]表示以i下标为结尾j下标为结尾的等差子序列个数
        //初始化
        //状态转移
        int sum = 0;
        for(int j  = 2; j < n; j++) {
            for(int i = 1; i < j; i++) {
                long a = 2L * nums[i]-nums[j];
                if(hash.containsKey(a)) {
                    for(int k : hash.get(a)) {
                        if(k < i) {
                            dp[i][j] += dp[k][i]+1;
                        }else {
                            break;//小优化
                        }
                    }
                }
                sum += dp[i][j];
            }
        }
        return sum;
    }
}